<!-- 任务基础信息页面-->
<template>
  <TCollapse title="基础数据信息">
    <!-- 搜索 -->
    <div class="do-search" style="display: flex;width: 100%;" >
      <div class="left-form" style="margin-right: 10px;">
        <MyForm ref="formRef" v-model="queryParams" :form-option="MyformOption" :select-list="dicLists" />
      </div>
      <div class="right-btn" style="display: flex;align-items: center;justify-content: right;margin-left: auto;">
        <el-button class="pms-button-primary" @click="createClick('doSearch')">查询</el-button>
        <el-button class="pms-button-primary" @click="createClick('reset')">重置</el-button>
      </div>
    </div>
    <div v-if="this.$route.query.type === 'todo' && noEdit" class="operate-btn">
      <el-button class="pms-button-primary" @click="createClick('addInfo')">新增</el-button>
      <el-button class="pms-button-primary" @click="createClick('refreshIfno')">更新</el-button>
      <el-button class="pms-button-primary" @click="createClick('delInfo')">删除</el-button>
    </div>
    <div style="margin-top: 20px;">
      <ElectronicTable
        id="id"
        ref="myTables"
        :columns="columns"
        :is-selection="true"
        :table-data="tableData"
        :select-list="selectList"
        :no-edit="noEdit"
        :types="this.$route.query.type"
        :task-info-obj="taskInfoObj"
        @handleSelection="handleSelection"
        @selectChangeFun="selectChangeFun"
        @changeInput="changeInput"
        @foucsChange="foucsChange"
        @refrshDosearch="doSearch"
      />
      <pagination
        v-if="pageParam.total > 10"
        :total="pageParam.total"
        :page.sync="pageParam.pageNum"
        :limit.sync="pageParam.pageSize"
        @pagination="doSearch"
      />
    </div>
    <div
      v-if="this.$route.query.type === 'todo' && suppierShow"
      style="display: flex;justify-content: center;align-items: center;margin-top: 10px;"
    >
      <el-button class="pms-button-primary" @click="createClick('confirmResult')">确认结果</el-button>
    </div>
  </TCollapse>
</template>

<script>
import TCollapse from '@/components/basic/TCollapse.vue'
import ElectronicTable from './ElectronicTable.vue'
import SysConst from '@/common/const'
import MyForm from '@/components/basic/myForm'
import { MyformOption, tableColumns, ENUM_TYPE_PROP, ENUM_TYPE, CONSOLE_MESSAGE, ENUM_TYPE_BACK } from '../setting'
import { queryBasicTask } from '@/api/attachManagement/electronicSign/electronicSignature'
import {
    getSingareTableInfo,
    upDateSingareTableInfo,
    saveSingareTableInfo,
    deleteSingareTableInfo,
    getSingareSelectInfo,
    getSingareProductSelectInfo,
    suppierConfirmFlow
} from '@/api/electSingnare/index'
export default {
    name: 'TaskBasicInfo',
    inject: ['workDetail'],
    components: {
        TCollapse,
        ElectronicTable,
        MyForm
    },
    data() {
        return {
            tableColumns,
            dicLists: {},
            MyformOption,
            queryParams: {},
            // 表头数据
            columns: [], // 供应商名称
            // 表格数据
            tableData: [
            ],
            // 下拉框的值
            selectList: {
            },
            // 分页信息
            pageParam: {
                pageSize: SysConst.PAGESIZE, // 每页显示val条
                pageNum: SysConst.CURRENT_PAGE, // 当前页
                total: SysConst.TOTAL // 总数
            },
            // 手动添加的数据
            addData: [],
            // 多选框选择数据
            checkData: [],
            saveCode: '',
            curentQuarter: '',
            taskInfoObj: {}, // 任务信息
            temporaryPreservation: {}
        }
    },
    computed: {
        newWorkDetail() {
            return this.workDetail()
        },
        noEdit() {
            return this.newWorkDetail.bizObject.nodeCode === 'electronicSeal_101'
        },
        suppierShow() {
            return this.newWorkDetail.bizObject.bizState === 'WD2'
        }
    },
    created() {
        this.getTaskBasicInfo()
    },
    methods: {
        async getTaskBasicInfo() {
            // 不允许编辑表格
            this.columns = !this.noEdit
                ? this.tableColumns.map((item) => {
                    return {
                        ...item,
                        isEdit: false,
                        isSelect: false
                    }
                })
                : this.tableColumns
            const params = {
                taskId: this.newWorkDetail?.bizObject?.bizSeq,
                workItemId: this.newWorkDetail?.bizObject?.nodeCode === 'electronicSeal_301' ? this.newWorkDetail.workItemID : null,
                pageNum: 1,
                pageSize: 10
            }
            const { code, data } = await queryBasicTask(params)
            if (+code === 200) {
                this.taskInfoObj = data.records[0]
                this.curentQuarter = data.records[0]?.taskQuarter
                this.doSearch()
                this.changeTableColunms(data.records[0]?.taskQuarter)
                this.getSelectDicData()
            }
        },
        // 处理季度月份
        changeTableColunms(global) {
            const ENUM_DATA_TYPE = {
                1: [1, 2, 3],
                2: [4, 5, 6],
                3: [7, 8, 9],
                4: [10, 11, 12]
            }
            this.columns = this.columns.map((item) => {
                return {
                    ...item,
                    label: ['scoreMonth1', 'scoreMonth2', 'scoreMonth3'].includes(
                        item.prop
                    )
                        ? getList(item)
                        : item.label
                }
            })
            function getList(item) {
                if (item.prop === 'scoreMonth1') {
                    return ENUM_DATA_TYPE[global][0] + item.label
                } else if (item.prop === 'scoreMonth2') {
                    return ENUM_DATA_TYPE[global][1] + item.label
                } else {
                    return ENUM_DATA_TYPE[global][2] + item.label
                }
            }
        },
        createClick(fun) {
            this[fun]()
        },
        // 供应商确认结果
        async confirmResult() {
            const { taskId } = this.taskInfoObj
            const { code, data } = await suppierConfirmFlow(taskId, this.tableData[0]?.supplierCode)
            if (+code === 200) {
                this.$message.success(data)
            }
        },
        // 新增数据
        addInfo() {
            if (this.addData.length >= 1) {
                this.$alert(`请保存当前数据后，再进行数据新增！`, '系统提示', {
                    confirmButtonText: '确定',
                    // 将字符串html化
                    dangerouslyUseHTMLString: true,
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary'
                })
                return
            }
            // 新增数据
            const saveData = {
                showSelect: true,
                prjCode: '',
                prjName: '',
                systemName: '',
                supplierCode: '',
                supplierName: '',
                supplierUserName: '',
                contractCode: '',
                workLoads: '',
                taxPrice: '',
                price: '',
                totalTaxAmount: '',
                totalAmount: '',
                taxDeducAmount: '',
                deducAmount: '',
                paymentTotalAmount: '',
                paymentTotalTaxAmount: '',
                avgScore: '',
                scoreMonth1: '',
                scoreMonth2: '',
                scoreMonth3: ''
            }
            this.tableData.unshift(saveData)
            this.addData.unshift(saveData)
        },
        // 刷新数据
        async refreshIfno() {
            // 代表没有选中数据
            if (this.checkData.length < 1) {
                this.$confirm('是否更新最新数据!', '系统提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
                }).then(() => {
                    this.updateTableData()
                }).catch(() => {
                    console.log('cancel')
                })
                return
            }
            this.updateTableData()
        },
        // 保存数据
        async reallySaveTable() {
            const copyData = JSON.parse(JSON.stringify(this.tableData)) || []
            copyData.forEach(item => {
                delete item.showSelect
            })
            // 保存的数据
            const filterList = copyData.filter((item) => {
                return Object.values(item).some(value => {
                    // 检查值是否不是以下“空”值之一：null, undefined, 空字符串
                    return value !== null && value !== undefined && value !== ''
                })
            })
            const { taskId, taskYear, taskQuarter } = this.taskInfoObj
            const resultList = filterList.map(item => {
                return {
                    ...item,
                    taskId,
                    taskQuarter,
                    taskYear
                }
            })
            const { code } = await saveSingareTableInfo(resultList, 0)
            if (+code === 200) {
                this.refreshTableData()
            }
        },
        // 更新表格数据
        async updateTableData() {
            // 过滤 新增的数据不进行更新
            const filtersListData = this.checkData?.filter(item => !item.showSelect)
            const transformedArray = filtersListData?.map(item => item?.summaryId)
            const resInfo = transformedArray.join(',')
            const { taskId, taskYear, taskQuarter } = this.taskInfoObj
            const updataParams = {
                taskId,
                taskYear,
                taskQuarter,
                summaryId: resInfo
            }
            console.log(CONSOLE_MESSAGE, '更新表格数据手动添加数据不做更新', updataParams)
            const { code } = await upDateSingareTableInfo(updataParams)
            if (+code === 200) {
                await this.refreshTableData()
                this.$message({
                    type: 'success',
                    message: '更新成功!'
                })
            }
        },
        // 删除数据
        delInfo() {
            if (this.checkData.length < 1) {
                this.$message.warning('请勾选数据后操作!')
                return
            }
            this.$confirm('是否确认删除?', '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
            })
                .then(async() => {
                    // 假删除
                    const shameData = this.checkData.filter(item => item.showSelect)
                    const _shameData = this.checkData.filter(item => !item.showSelect)
                    if (shameData.length > 0 && this.checkData.length === 1) {
                        this.addData = []
                        this.saveCode = 200
                        // 刷新列表接口
                        this.doSearch()
                        return
                    }
                    // 使用map方法转换数组
                    const transformedArray = _shameData.map(item => item?.summaryId)
                    const { code } = await deleteSingareTableInfo(transformedArray)
                    if (+code === 200) {
                        // 删除逻辑
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        })
                        this.doSearch()
                    }
                })
                .catch(() => {
                    console.log('cancel')
                })
        },
        // 查询
        async doSearch(item) {
            const _userInfo = JSON.parse(sessionStorage.getItem('SET_LOGINDATA')) || {}
            let flagName = ''
            let flagNames = ''
            let _workItemId = ''
            if (this.newWorkDetail?.bizObject?.nodeCode === 'electronicSeal_102') {
                flagName = _userInfo?.loginName
            } else if (this.newWorkDetail?.bizObject?.nodeCode === 'electronicSeal_301') {
                _workItemId = this.newWorkDetail?.workItemID
                flagNames = _userInfo?.loginName
            } else {
                flagName = ''
                _workItemId = ''
                flagNames = ''
            }
            const params = {
                pageNum: item?.page || SysConst.CURRENT_PAGE,
                pageSize: item?.limit || SysConst.PAGESIZE,
                param: {
                    taskId: this.taskInfoObj?.taskId,
                    taskYear: this.taskInfoObj?.taskYear,
                    taskQuarter: this.taskInfoObj?.taskQuarter,
                    supplierUserCode: flagName,
                    workItemId: _workItemId,
                    projectManagerCode: flagNames,
                    ...this.queryParams
                }
            }
            const { code, data } = await getSingareTableInfo(params)
            if (+code === 200) {
                console.log(CONSOLE_MESSAGE, '获取表格数据', code, data, params)
                this.tableData = data?.list || []
                this.pageParam.total = data?.total || 0
                this.pageParam.pageSize = item?.limit || SysConst.PAGESIZE
                this.pageParam.pageNum = item?.page || SysConst.CURRENT_PAGE
                // this.getControCodeInfo()
                this.checkData = []
                this.addData = []
                this.saveCode = 200
            }
        },
        // 获取供应商下拉框数据
        async getControCodeInfo() {
            const { taskId, taskYear, taskQuarter } = this.taskInfoObj
            const params = {
                taskId,
                taskYear,
                taskQuarter,
                prjCode: '',
                supplierCode: '',
                contractCode: ''
            }
            const uniqueTable = this.uniqueArrIdAndName(this.tableData)
            const _arrIndex = [0, 1, 2, 3] // 循环4次
            const finishResult = {
                0: {},
                1: {},
                2: {},
                3: {}
            }
            // 先循环次数 在循环表格
            for (let j = 0; j < _arrIndex.length; j++) {
                for (let i = 0; i < uniqueTable.length; i++) {
                    params.prjCode = uniqueTable[i].prjCode
                    params.supplierCode = uniqueTable[i].supplierCode
                    params.contractCode = uniqueTable[i].contractCode
                    const result = await this.looperData(params, _arrIndex[j])
                    let content = params.prjCode
                    if ([2, 3].includes(_arrIndex[j])) {
                        content = params?.prjCode + params?.supplierCode
                    }
                    finishResult[_arrIndex[j]][content] = result
                }
            }
            for (const k in finishResult) {
                this.$set(this.temporaryPreservation, ENUM_TYPE[k], {})
                this.$set(this.temporaryPreservation[ENUM_TYPE[k]], k, finishResult[k])
            }
            console.log(this.temporaryPreservation, CONSOLE_MESSAGE)
        },
        uniqueArrIdAndName(arr) {
            return arr.reduce((acc, item) => {
                // 构造一个唯一的键，用于映射对象中，这里使用 id 和 name 的组合
                const uniqueKey = `${item.prjCode}-${item.supplierCode}`
                // 如果映射对象中不存在当前 item 的 uniqueKey，则添加到结果数组和映射对象中
                if (!acc.map.has(uniqueKey)) {
                    acc.result.push(item)
                    acc.map.set(uniqueKey, true)
                }
                return acc
            }, { result: [], map: new Map() }).result
        },
        async looperData(params, type) {
            const { code, data } = await getSingareSelectInfo(params, type)
            if (+code === 200) {
                const resultList = data.map(item => {
                    return getObjs(type, item)
                })
                return resultList
            }
            function getObjs(_type, item) {
                if (+_type === 0) {
                    return {
                        prjCode: item?.code,
                        prjName: item?.name
                    }
                } else if (+_type === 1) {
                    return {
                        supplierCode: item?.code,
                        supplierName: item?.name
                    }
                } else if (+_type === 2) {
                    return {
                        contractCode: item.code,
                        contractName: item.name
                    }
                } else {
                    return {
                        supplierUserName: item?.name,
                        supplierUserCode: item?.code
                    }
                }
            }
        },
        // 重置
        reset() {
            this.$refs.formRef.reset()
        },
        // 多选框选择数据
        handleSelection(data) {
            console.log(CONSOLE_MESSAGE, data, '选择数据')
            this.checkData = data
        },
        /**
         *
         * @param operateType 0：项目编码 1：供应商编码 2：合同编码 3: 供应商人员
         */
        // 下拉框获取项目编码/项目名称
        async getSelectDicData(selectObj, operateType = 0) {
            const { taskId, taskYear, taskQuarter } = this.taskInfoObj
            const params = {
                taskId,
                taskYear,
                taskQuarter,
                prjCode: selectObj?.prjCode ? selectObj?.prjCode : '',
                supplierCode: selectObj?.supplierCode ? selectObj?.supplierCode : '',
                contractCode: selectObj?.contractCode ? selectObj?.contractCode : ''
            }
            const { code, data } = await getSingareSelectInfo(params, operateType)
            if (+code === 200) {
                this.solveSelectInfo(data, operateType)
            }
        },
        /**
         *
         * @param data
         * @param type  0：项目编码 1：供应商编码 2：合同编码 3: 供应商人员
         */
        async solveSelectInfo(data, type) {
            const result = this.processingDataLogic(data, type)
            this.$set(this.selectList, ENUM_TYPE[type], result)
            console.log(CONSOLE_MESSAGE, this.selectList, '获取下拉框最新数据')
        },
        processingDataLogic(data, type) {
            const resultList = data.map(item => {
                return getObjs(type, item)
            })
            function getObjs(_type, item) {
                if (+_type === 0) {
                    return {
                        prjCode: item.code,
                        prjName: item.name
                    }
                } else if (+_type === 1) {
                    return {
                        supplierCode: item.code,
                        supplierName: item.name
                    }
                } else if (+_type === 2) {
                    return {
                        contractCode: item.code,
                        contractName: item.name
                    }
                } else {
                    return {
                        supplierUserName: item.name,
                        supplierUserCode: item.code
                    }
                }
            }
            return resultList
        },
        // 获取下拉框其他数据
        async getSelectProductData(row) {
            const { taskId, taskYear, taskQuarter } = this.taskInfoObj
            const params = {
                taskId,
                taskYear,
                taskQuarter,
                prjCode: row.prjCode,
                supplierCode: row.supplierCode,
                contractCode: row.contractCode,
                systemName: row.systemName
            }
            const { code, data } = await getSingareProductSelectInfo(params)
            if (+code === 200) {
                for (const k in data) {
                    if (row[k] === '' || row[k] === null || +row[k] === 0) {
                        row[k] = data[k]
                    }
                }
            }
            delete row?.showSelect
            delete row?.code
            const finishCode = await this.singleSaveInfo(row, 0, false)
            if (+finishCode !== 200) {
                return
            }
            this.addData = []
            this.saveCode = 200
        },
        // 下拉框回显选择数据
        async selectChangeFun(item, row, label, types) {
            // 自己手动添加的showSelect属性删掉
            this.changeSelectValue(item, row, label, types)
            console.log(CONSOLE_MESSAGE, item, row, label, types, '下拉框选完准备保存数据')
            const paramsObj = {
                prjCode: row.prjCode,
                supplierCode: row.supplierCode,
                contractCode: row.contractCode
            }
            const finshType = this.backType(paramsObj, item)

            // 需要调其他接口获取完整数据
            if (item === 'contractCode') {
                await this.getSelectProductData(row)
            } else {
                for (let i = 0; i < finshType.length; i++) {
                    await this.getSelectDicData(paramsObj, finshType[i])
                }
            }
            if (this.selectList['SUPPIER_USER']?.length === 1 && ['supplierCode', 'supplierName'].includes(item)) {
                let _copyrow = JSON.parse(JSON.stringify(row))
                _copyrow.supplierUserName = this.selectList['SUPPIER_USER'][0].supplierUserName
                _copyrow.supplierUserCode = this.selectList['SUPPIER_USER'][0].supplierUserCode
                this.onlySelectPersonCheckSave('supplierUserName', _copyrow, label)
                return
            }
            // 人员保存
            this.onlySelectPersonCheckSave(item, row, label)
        },
        backType(paramsObj, item) {
            let finshType = [0]
            if (paramsObj.prjCode !== '' && ['prjCode', 'prjName'].includes(item)) {
                finshType = [1]
            } else if (paramsObj.prjCode !== '' && paramsObj.supplierCode !== '' && ['supplierCode', 'supplierName'].includes(item)) {
                finshType = [2, 3]
            } else {
                finshType = [2]
            }
            return finshType
        },
        // 只有人员选择以后才可以保存
        onlySelectPersonCheckSave(item, row, label) {
            if (item !== 'supplierUserName') {
                return
            }
            // 保存的逻辑
            if (row.showSelect) {
                this.addSaveSelectInfo(item, row, label)
            } else {
                this.originalSaveSelectInfo(item, row, label)
            }
        },
        // 互相回填值
        changeSelectValue(item, row, label, types) {
            if (['prjCode', 'prjName', 'supplierCode', 'supplierName', 'contractCode', 'supplierUserName'].includes(item)) {
                row[ENUM_TYPE_PROP[item]] = this.calcData(ENUM_TYPE_PROP[item], ENUM_TYPE_PROP[types], label)
            }
        },
        calcData(type, selectType, label) {
            const result = this.selectList[selectType]?.find(item => item[ENUM_TYPE_PROP[type]] === label)
            return result[type]
        },
        // 原始数据下拉框保存
        async originalSaveSelectInfo(item, row, label) {
            console.log(CONSOLE_MESSAGE, '原始数据下拉框保存人员实时保存', row)
            if (row?.supplierUserName === '' || row?.supplierUserName == null) {
                return
            }
            // 调用保存接口
            this.singleSaveInfo(row, 1)
        },
        // 新增数据下拉框保存
        async addSaveSelectInfo(item, row, label) {
            console.log(CONSOLE_MESSAGE, '新增数据下拉框保存人员实时保存', row)
            // 自己手动添加的showSelect属性删掉 选择人员以后才可以实时保存
            if (row?.supplierUserName === '' || row?.supplierUserName == null) {
                return
            }
            const deepRow = JSON.parse(JSON.stringify(row))
            delete deepRow?.showSelect
            delete deepRow?.code
            const code = await this.singleSaveInfo(deepRow, 1)
            if (+code === 200) {
                this.addData = []
                this.saveCode = 200
            }
        },
        async singleSaveInfo(row, type = 1, showMessage = true) {
            const { taskId, taskYear, taskQuarter } = this.taskInfoObj
            const params = [{
                ...row,
                taskId,
                taskYear,
                taskQuarter
            }]
            const { code } = await saveSingareTableInfo(params, type)
            if (+code === 200) {
                if (showMessage) {
                    this.$message.success('保存成功！')
                }
                this.doSearch()
                return code
            }
        },
        // 表格编辑回显的数值暂时没有用
        async changeInput(item, index, row) {
            console.log(CONSOLE_MESSAGE, '表格单元格编辑回显数值', item, index, row)
        },
        // 刷新表格最新数据方法
        async refreshTableData() {
            console.log(CONSOLE_MESSAGE, '刷新表格最新数据')
            this.doSearch()
        },
        async foucsChange(row, item, selectType) {
            // 没有项目编码 全部置空
            if (row.prjName === '' || row.prjName === null) {
                this.$set(this.selectList, 'SUPPIER_CODE', [])
                this.$set(this.selectList, 'CONTRACT_CODE', [])
                this.$set(this.selectList, 'SUPPIER_USER', [])
                console.log(CONSOLE_MESSAGE, '没有项目编码置空', this.selectList)
                return
            }
            // 供应商编码存在可以进行调接口
            if ((row.supplierCode !== '' && row.supplierCode !== null) || selectType === 'SUPPIER_CODE') {
                this.getSelectDicData(row, ENUM_TYPE_BACK[selectType])
                console.log(CONSOLE_MESSAGE, '供应商编码存在可以进行调接口', this.selectList)
            } else {
                this.$set(this.selectList, 'CONTRACT_CODE', [])
                this.$set(this.selectList, 'SUPPIER_USER', [])
                console.log(CONSOLE_MESSAGE, '没有供应商编码置空', this.selectList)
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.do-search {
    // display: flex;
    // justify-content: space-between;
    // align-items: center;

    // .left-form {
    //     display: flex;
    //     align-items: center;
    //     width: 85%;

    //     .input-container {
    //         display: flex;
    //         align-items: center;

    //         span {
    //             width: 110px;
    //             display: block;
    //             color: #606266;
    //         }
    //     }
    // }
}

.operate-btn {
    text-align: right;
    margin-top: 20px;
}
</style>
